package webserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class HTTPResponse {
	HTTPRequest request;
	//this is the final response generated
	String response;
	//root path of the server
	String root="D:/root";
	
	public HTTPResponse(HTTPRequest request)  {
		this.request=request;
		//now we have to open a file mentioned in request
		File file=new File(root+request.fileName);
		System.out.println(root+request.fileName);
		try{
		//to read this file 
		FileInputStream fis=new FileInputStream(file);
		response="HTTP/1.1 200 \r\n"; //version for http and 200 for status code
		response+="Server: our java server1.0 \r\n"; //identity of server
		response+="Content-Type: text/html \r\n"; // response is in html format
		response+="Connection:close \r\n";
		response+="Content-Length:" +file.length()+"\r\n"; //length of response
		response+="\r\n";// after blanck line we have to append file data
		
		int s;
		while((s=fis.read())!=-1){
			response+=(char)s;
			
		}
		
		fis.close();
		//200 means everything is ok
	}catch(FileNotFoundException e){
		//if we dont get file then error 404
		response=response.replace("200", "404");
		e.printStackTrace();
		
		
	}
		catch(Exception e){
		//then error 500
			response=response.replace("200", "500");
			e.printStackTrace();
		
		
	}}

}
